package cn.lmxdev.ptms.service.impl;

import cn.lmxdev.ptms.bean.exception.BizException;
import cn.lmxdev.ptms.bean.table.TDepartment;
import cn.lmxdev.ptms.dao.IDepartmentDao;
import cn.lmxdev.ptms.service.IDepartmentServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class DepartmentServletImpl implements IDepartmentServlet {
    private final IDepartmentDao departmentDao;

    @Autowired
    public DepartmentServletImpl(
            IDepartmentDao departmentDao
    ) {
        this.departmentDao = departmentDao;
    }

    @Override
    @Transactional
    public TDepartment get(Long id) {
        return this.departmentDao.find(id);
    }

    @Override
    @Transactional
    public long add(TDepartment department) {
        // 判断名称是否已经存在
        TDepartment departmentByName = this.departmentDao.findByName(department.getName());
        if (departmentByName != null && departmentByName.getId() > 0)
            throw new BizException("操作失败，该名称已经存在");

        // 插入数据
        if (!this.departmentDao.insert(department))
            throw new BizException("操作失败");

        // 返回ID
        return department.getId();
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 删除数据
        if (!this.departmentDao.delete(id))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public void edit(TDepartment department) {
        // 查询旧数据
        TDepartment oldDepartment = this.departmentDao.find(department.getId());

        // 判断名称是否已经存在
        TDepartment departmentByName = this.departmentDao.findByName(department.getName());
        if (departmentByName != null && !Objects.equals(departmentByName.getId(), oldDepartment.getId()))
            throw new BizException("操作失败，该名称已经存在");

        // 更新属性
        oldDepartment
                .setDepartmentHeadId(department.getDepartmentHeadId())
                .setName(department.getName());

        // 修改数据
        if (!this.departmentDao.update(oldDepartment))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public long count(TDepartment department) {
        return this.departmentDao.count(department);
    }

    @Override
    @Transactional
    public List<TDepartment> list(Long limit, Long page, TDepartment department) {
        return this.departmentDao.select(page != null ? (page - 1) * limit : null, limit, department);
    }
}
